package top.easyblog.core.aspect;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.easyblog.common.constant.Constants;
import top.easyblog.common.exception.DLockException;
import top.easyblog.common.response.ShortlinkResultCode;
import top.easyblog.core.annotation.DLock;
import top.easyblog.core.annotation.RequestId;
import top.easyblog.core.support.lock.DistributedLock;
import top.easyblog.core.support.lock.RedisDistributeLockFactory;
import top.easyblog.core.util.IdGenerator;
import top.easyblog.core.util.SpELUtils;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author: frank.huang
 * @date: 2023-12-21 22:19
 */
@Slf4j
@Aspect
@Component
public class RequestIdAspect {


    @Pointcut("@annotation(top.easyblog.core.annotation.RequestId)")
    public void requestId() {
    }


    @Around("requestId()")
    public Object processApiRequest(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();

        if (!method.isAnnotationPresent(RequestId.class)) {
            throw new DLockException(ShortlinkResultCode.REQUESTID_ANNOTATION_NOT_FOUND,
                    String.format("方法[%s]签名未找到RequestId注解", method.getName()));
        }

        String requestId = MDC.get(Constants.REQUEST_ID);
        if (StringUtils.isBlank(requestId)) {
            MDC.put(Constants.REQUEST_ID, IdGenerator.getRequestId());
        }

        return pjp.proceed(pjp.getArgs());
    }

}
